import axios from 'axios'
import jsonp from 'jsonp'
import qs from 'qs'
import store from '@/store'

const timeout = 3000
const jsonpConfig = {
  timeout
}
const axiosConfig = {
  timeout,
  withCredentials: true,
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  }
}

//异步前置拦截器
axios.interceptors.request.use(
  config => {
    // 如果用户已经登录，在请求头里面添加token
    if (store.getters.gIsLogin) {
      config.headers.token = store.state.sLoginInfo.token
    }
    //如果用户已经登陆，判断toke是否需要置换
    if(store.getters.gIsLogin){
      //获取过期时间
      let extTime = store.state.sLoginInfo.extTime;
      console.log(extTime+"用户过期时间");
      //获取当前时间
      let currentTime = (new Date()).getTime();
      console.log(currentTime+"当前时间");
     
      //登陆的时间
      let logTime = store.state.sLoginInfo.genTime;
      console.log(logTime+"登陆时间");

      console.log(extTime-logTime);


    

      //判断是否需要重新登陆
      if(currentTime < extTime){
        //判断token剩余五分钟，判断条件 当前时间小于退出时间 && 当前时间大于115分钟
        // 6900000
        if(currentTime < extTime && currentTime > (logTime + 6900000)){
          config.headers.resetToken = true;
        }else{
          config.headers.resetToken = false;
        }
      }else{
        //跳转登录页
        location.href="http://localhost:8080/#/login"
        console.log("请重新登陆!");
      }
      
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

//异步后置拦截器
axios.interceptors.response.use(res=>{
  //获取置换后的token
  let token = res.headers.tokenvo
  if(token != undefined){
    //将前端的Token进行置换
    const loginInfo = JSON.parse(token)  
    store.commit('mLogin', loginInfo)
  }
  //判断是否执行的操作需要的登陆
  if(res.data.errorCode == "1222"){
    //跳转登录页
    location.href="http://localhost:8080/#/login"
  }
  return res;
})

export default (method, url, option = {}) => {
  let isPost = true
  const config = option.config || {}
  delete option.config

  method = (method || '').toUpperCase()

  if (['GET', 'DELETE', 'HEAD', 'JSONP'].indexOf(method) > -1) {
    const query = qs.stringify(option, {
      addQueryPrefix: true
    })
    isPost = false

    if (url.indexOf('?') > -1) {
      url += query.replace('?', '&')
    } else {
      url += query
    }
  }

  if (method === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {...jsonpConfig, ...config}, (err, data) => {
        if (err) return reject(err)
        resolve(data)
      })
    })
  }

  const makeConfig = {method, url}
  if (isPost) {
    makeConfig.data = option
  }

  return axios({
    ...axiosConfig,
    ...makeConfig,
    ...config
  }).then(ret => ret.data)
}
